﻿using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using System.Resources;

namespace WSPay.Common {
    public static class EnumExtensions {
        public static T ToEnum<T>(this int value) where T : struct {
            return (T) Enum.ToObject(typeof (T), value);
        }

        public static string ToLocalizable(this Enum value, Type language)
        {
            var customAttr = (LocalizableAttribute)Attribute.GetCustomAttribute(value.GetType(), typeof(LocalizableAttribute));
            var resources = new ResourceManager(language);
            var prefix = customAttr.Prefix;
            if (string.IsNullOrEmpty(prefix))
            {
                prefix = value.GetType().Name;
            }

            string rk = String.Format("{0}_{1}", prefix, value);
            string localiza = resources.GetString(rk);
            if (localiza == null)
            {
                return !string.IsNullOrWhiteSpace(customAttr.Default) ? customAttr.Default : value.ToString();
            }
            return localiza;
        }

        public static string ToLocalizable(this Enum value)
        {
            var localiza = value.ToDescription();
            return string.IsNullOrWhiteSpace(localiza) ? value.ToString() : localiza;
        }

        public static string ToDescription(this Enum value)
        {
            return EnumItemDescriptionAttribute.GetDisplayValue(value, value.GetType());
        }

        public static IEnumerable<KeyValuePair<int, Enum>> ToKeyValueParir(this Enum e)
        {
            return (from Enum d in e.GetType().GetEnumValues() select new KeyValuePair<int, Enum>(Convert.ToInt32(d), d)).ToList();
        }
    }
}